//
//  ConnectionDelegate.m
//  mUBB
//
//  Created by Cosmin Stirbu on 1/13/13.
//  Copyright (c) 2013 Cosmin Stirbu. All rights reserved.
//

#import "ConnectionDelegate.h"
#import "Constants.h"

#define MESSAGE_TAG @"Message"

@implementation ConnectionDelegate

@synthesize delegate, ticket;

- (id)initWithDelegate:(id)aDelegate ticket:(Ticket *)aTicket{
    self = [super init];
    [self setDelegate:aDelegate];
    [self setTicket:aTicket];
    return self;
}

- (void)didReceiveResponse:(WSResponse *)response {
    _response = response;
    if (response.statusCode == StatusCodeSuccess || response.statusCode == StatusCodeNoContent) {
        // Success call
        [self handleSuccess:response];
    } else {
        // Failed call
        [self parseErrorMessage:response];
    }
}

- (void)parseErrorMessage:(WSResponse *)response {
    _response = response;
    WSError *error = [[WSError alloc] initWithErrorCode:response.statusCode andErrorMessage:nil];
    id responseData = [response.data objectFromJSONData];
    if ([responseData isKindOfClass:[NSDictionary class]]) {
        // If we received a dictionary with the MESSAGE key
        error.errorMessage = [responseData getJSONObjectForKey:MESSAGE_TAG];
    }
    [self handleError:error];
    
}

- (void)didFailWithError:(NSError *)error {
    // Connection error
    [self handleError:[[WSError alloc] initWithErrorCode:StatusCodeConnectionError andErrorMessage:NSLocalizedString(@"MESSAGE_CONNECTION_ERROR", nil)]];
}

- (void)handleSuccess:(WSResponse *)response {
    // Force sublcasses to implement this method
    [self doesNotRecognizeSelector:_cmd];
}

- (void)handleError:(WSError *)error {
    // Force subclasses to implement this method
    [self doesNotRecognizeSelector:_cmd];
}

@end
